# -*- coding: utf8 -*-
import json
import threading
from datetime import datetime
import requests
import time
import hmac
import hashlib
import base64
import urllib.parse
#python 3.8



class DingDingHelper(object):
    def __init__(self):
        pass

    def __new__(cls):
        mutex = threading.Lock()
        mutex.acquire()
        if not hasattr(cls, 'instance'):
            cls.instance = super(DingDingHelper, cls).__new__(cls)

        mutex.release()
        return cls.instance

    def send_message(self,title,txt,atmobile):
        timestamp = str(round(time.time() * 1000))
        secret = 'XXXXXXXXX'
        secret_enc = secret.encode('utf-8')
        string_to_sign = '{}\n{}'.format(timestamp, secret)
        string_to_sign_enc = string_to_sign.encode('utf-8')
        hmac_code = hmac.new(secret_enc, string_to_sign_enc, digestmod=hashlib.sha256).digest()
        sign = urllib.parse.quote_plus(base64.b64encode(hmac_code))
        print(timestamp)
        print(sign)
        atmobilearr = []
        isAtAll = True
        if atmobile!="":
            isAtAll = False
            atmobilesplit = atmobile.split(',')
            for mobile in atmobilesplit:
                atmobilearr.append(mobile)
        if not title:
            title="视频告警信息"
        
        url = 'https://oapi.dingtalk.com/robot/send?access_token=78dd6f7d86283d42a2a55778721df8af652d16ab56ca8237d2ffd75ef747884a&timestamp='+timestamp+'&sign='+sign
        data = {
            "msgtype":"markdown",#采用MarkDown语法
            "markdown":{
                "title":title,
                "text": txt
            },
            "at": {
                "atMobiles": atmobilearr,
                "isAtAll": isAtAll
            }
        }
        headers = {'Content-Type': 'application/json;charset=utf-8'}
        send_data = json.dumps(data).encode('utf-8')
        requests.post(url=url, data=send_data, headers=headers)




